import os
import re
import urllib2


class Updater(object):

    def __init__(self,aws_access_key,aws_secret_access_key):

        os.environ['AWS_ACCESS_KEY_ID'] = aws_access_key
        os.environ['AWS_SECRET_ACCESS_KEY'] = aws_secret_access_key

    def get_ip(self):
        """
        Get the public ip address of the current machine
        """
        #get the actual ip address
        buffer = urllib2.urlopen('http://wtfismyip.com/text')
        results=buffer.read()
        ip = re.compile('(([2][5][0-5]\.)|([2][0-4][0-9]\.)|([0-1]?[0-9]?[0-9]\.)){3}'
                +'(([2][5][0-5])|([2][0-4][0-9])|([0-1]?[0-9]?[0-9]))')

        #look for an ip address in the response
        match = ip.search(results)
        return match.group()

    def set_zone_ip(self,name,ip_address):
        """
        Set the zone ip address given the zone
        """

        from area53 import route53

        zone = route53.get_zone(name)

        if not zone:
            return

        record_to_update = zone.get_a(name)

        if record_to_update and zone:
            zone.update_a(record_to_update.name,ip_address,record_to_update.ttl)

        return